import MSData
import ConfigParser
import os

if os.name == 'posix':  DIRSEP = '/'
if os.name == 'nt':     DIRSEP = '\\'
config = ConfigParser.RawConfigParser()
ready = False

def init(path, initEmpty=True):
    global config, ready
    config.read(path + DIRSEP + 'config.cfg')
    if initEmpty:
        if not 'main' in config.sections(): config.add_section('main')
        if not config.has_option('main','host'): config.set('main','host','0.0.0.0')
        if not config.has_option('main','port'): config.set('main','port','8081')
        if not config.has_option('main','root'): config.set('main','root', path)

        config.set('main','js', config.get('main','root') + DIRSEP + 'js' + DIRSEP)
        config.set('main','css', config.get('main','root') + DIRSEP + 'css' + DIRSEP)
        config.set('main','html', config.get('main','root') + DIRSEP + 'www-data' + DIRSEP)
        config.set('main','image', config.get('main', 'root') + DIRSEP + 'images' + DIRSEP)
        config.set('main','dbpath', config.get('main','root') + DIRSEP + 'db' + DIRSEP)
        if not os.path.exists(config.get('main', 'dbpath')):
            os.makedirs(config.get('main','dbpath'))

        if not 'msdb' in config.sections(): config.add_section('msdb')
        if not config.has_option('msdb','host'): config.set('msdb','host','localhost')
        if not config.has_option('msdb','port'): config.set('msdb','port','1')
        if not config.has_option('msdb','dbname'): config.set('msdb','dbname','noname')
        if not config.has_option('msdb','user'): config.set('msdb','user','mssa')
        if not config.has_option('msdb','pwd'): config.set('msdb','pwd','msms')

        if not 'msapi' in config.sections(): config.add_section('msapi')
        if not config.has_option('msapi','url'): config.set('msapi', 'url', 'localhost')

        if not 'mswriter' in config.sections(): config.add_section('mswriter')
        if not config.has_option('mswriter','port'): config.set('mswriter', 'port', 0)
        if not config.has_option('mswriter','read_timeout'): config.set('mswriter', 'read_timeout', 5)
        if not config.has_option('mswriter','write_timeout'): config.set('mswriter', 'write_timeout', 5)

    ready = True

def write(path):
    global config, ready
    if not ready: return
    f = open(path + DIRSEP + 'config.cfg', 'w')
    f.write('[main]\n')
    f.write('host = %s\n' % str(config.get('main', 'host')))
    f.write('port = %s\n' % str(config.get('main', 'port')))
    f.write('root = %s\n' % str(config.get('main', 'root')))
    f.write('[msdb]\n')
    f.write('host = %s\n' % str(config.get('msdb', 'host')))
    f.write('port = %s\n' % str(config.get('msdb', 'port')))
    f.write('dbname = %s\n' % str(config.get('msdb', 'dbname')))
    f.write('[mswriter]\n')
    f.write('port = %s\n' % str(config.get('mswriter', 'port')))
    f.write('read_timeout = %s\n' % str(config.get('mswriter', 'read_timeout')))
    f.write('write_timeout = %s\n' % str(config.get('mswriter', 'write_timeout')))
    f.close()

#backward compat
def parseCfgLine(CfgLine):
    s = CfgLine.strip().split(' ')
    e = {}
    for prop in s[0:len(s)]:
        prop = prop.split('=')
        e[prop[0]] = prop[1]
    return e

def readProcessorConfig(Processor, ConfigFName):
    try:
        f = open(ConfigFName, 'r')
        cdata = f.readlines()
        for s in cdata:
            try:
                e = parseCfgLine(s)
                if e['enable'] != 'yes':
                    continue
                if   e['module'] == 'staticFirebird':
                    Processor.dbFirebirdStaticParams = (e['db_path'], e['db_user'], e['db_pass'])
                elif e['module'] == 'staticMySQL':
                    Processor.dbMySQLStaticParams = (e['db_host'], e['db_name'], e['db_user'], e['db_pass'])
                elif e['module'] == 'mobileMySQL':
                    Processor.dbMySQLMobileParams = (e['db_host'], e['db_name'], e['db_user'], e['db_pass'])
                elif e['module'] == 'objectStorage':
                    Processor.storageRoot = e['storage_root']
                elif e['module'] == 'cesarSender':
                    Processor.cesarConnectionParam = (e['host'], e['port'])
            except (Exception), err:
                raise RuntimeError('failed to parse Processor config line: %s exception: %s' % (s, str(err)))
                continue
    except (Exception), err:
            raise RuntimeError('failed to parse Processor config at all with exception: %s' % (str(err)))
            Processor.dbFirebirdStaticParams = None
            Processor.dbMySQLStaticParams = None
            Processor.dbMySQLMobileParams = None

def readObjectsConfig(ConfigFName):
    objects = []
    try:
        f = open(ConfigFName, 'r')
        cdata = f.readlines()
        for s in cdata:
            try:
                e = parseCfgLine(s)
                objId       = int(e['obj_id'])
                objName     = e['obj_name']
                objSkey     = e['obj_skey']
		o = MSData.MSObject()
                o.objectName = objName
                o.objectSKey = objSkey
                o.objectPCNId = objId
                objects.append(o)
            except (Exception), err:
                raise RuntimeError('failed to parse Object config line: %s exception: %s' % (s, str(err)))
                #TBD
                continue
    except (Exception), err:
            raise RuntimeError('failed to parse Object config at all with exception: %s' % (str(err)))
    return objects
